package jdbc;

import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @classname:DBHelper
 * @description:
 * @author: Mr.Z
 * @date: 2020/12/27 16:10
 * @version: 0.1
 * @since:1.8
 */
public class DBHelper {
    private DBHelper() {
    }

    private static ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal() {
        @SneakyThrows
        @Override
        protected Connection initialValue() {
              return DriverManager.getConnection(PropUtil.getValue("jdbc.url"), PropUtil.getValue("jdbc.username"), PropUtil.getValue("jdbc.password"));
        }
    };


    public static Connection getMysqlCon() {
        return THREAD_LOCAL.get();
    }

    public static void closeCon(Connection connection) {

        try {
            if (connection != null){
                connection.close();
                THREAD_LOCAL.remove();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {


        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                for (int i1 = 0; i1 < 3; i1++) {
                    System.out.println(Thread.currentThread().getName() + "===" + DBHelper.getMysqlCon());
                }
            }).start();
        }
    }
}
